package com.qfedu.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.config.RocketmqConfig;
import com.qfedu.param.DynamicAdd;
import com.qfedu.provider.entity.*;
import com.qfedu.provider.mapper.*;
import com.qfedu.provider.service.DbDynamicsService;
import com.qfedu.provider.util.MyMinioUtil;
import com.qfedu.utils.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
* @author Administrator
* @description 针对表【db_dynamics(动态，图文混排)】的数据库操作Service实现
* @createDate 2024-11-23 11:16:39
*/
@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
public class DbDynamicsServiceImpl extends ServiceImpl<DbDynamicsMapper, DbDynamics>
    implements DbDynamicsService{

    private final DbDynamicsMapper dbDynamicsMapper;
    private final DbDynamicImagesMapper dbDynamicImagesMapper;
    private final DbDynamicLogMapper dbDynamicLogMapper;
    private final DbProductTypeMapper dbProductTypeMapper;
    private final DbUserMapper dbUserMapper;
    private final RocketMQTemplate rocketMQTemplate;

    @Override
    public R queryAll() {
        LambdaQueryWrapper<DbDynamics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DbDynamics::getStatus,1);
        wrapper.eq(DbDynamics::getDeleted,1);
        List<DbDynamics> dbDynamics = dbDynamicsMapper.selectList(wrapper);
        if (dbDynamics.size()==0){
            return R.error("网络出差了，暂无动态");
        }
        for (int i = 0; i < dbDynamics.size(); i++) {
            LambdaQueryWrapper<DbDynamicImages> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DbDynamicImages::getDynamicsId, dbDynamics.get(i).getId());
            List<DbDynamicImages> dbDynamicImages = dbDynamicImagesMapper.selectList(wrapper1);
            dbDynamics.get(i).setDbDynamicImages(dbDynamicImages);
        }
        return R.ok(dbDynamics);
    }

    @Override
    public R addDynamic(DynamicAdd dynamicAdd,String ip) {
        //1 校验
        if (!StringUtils.hasLength(dynamicAdd.getUserId())){
            return R.error("用户id不能为空");
        }
        if (!StringUtils.hasLength(dynamicAdd.getDescription())){
            return R.error("动态描述不能为空");
        }
        if (dynamicAdd.getTypeId()==null){
            return R.error("动态类型不能为空");
        }
        //2 新增
        DbDynamics dbDynamics = new DbDynamics(dynamicAdd.getUserId(),dynamicAdd.getDescription(),dynamicAdd.getTypeId(), dynamicAdd.getDisplayUrl());

        LambdaQueryWrapper<DbDynamicImages> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DbDynamicImages::getDynamicsId,dbDynamics.getId());
        List<DbDynamicImages> dbDynamicImages = dbDynamicImagesMapper.selectList(wrapper);
//        if (dbDynamicImages.size()==0){
//            return R.error("动态图片不能为空");
//        }
        dbDynamics.setDbDynamicImages(dbDynamicImages);
        //默认发布图文动态
        dbDynamics.setProductTypeId(1);

        if(dbDynamicsMapper.insert(dbDynamics)>0){
            log.info("发布动态成功，进行审核");
        }

        rocketMQTemplate.convertAndSend(RocketmqConfig.TOPIC_MOODS,dbDynamics.getId());

        return R.ok("发布动态成功");

    }


    @Override
    public R removeDynamic(Integer did,String ip) {
        DbDynamics dbDynamics = dbDynamicsMapper.selectById(did);
        if (dbDynamics==null){
            return R.error("动态不存在");
        }
        dbDynamics.setDeleted(0);

        DbProductType dbProductType = dbProductTypeMapper.selectById(dbDynamics.getTypeId());
        String type = dbProductType.getType();
        DbUser dbUser = dbUserMapper.selectById(dbDynamics.getUserId());
        String nickName = dbUser.getNickName();

        if(dbDynamicsMapper.updateById(dbDynamics)>0){
            dbDynamicLogMapper.insert(new DbDynamicLog(dbDynamics.getUserId(),type,""+dbDynamics.getId(),ip,nickName+"删除了一条动态"));

            LambdaQueryWrapper<DbDynamicImages> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DbDynamicImages::getDynamicsId,did);
            wrapper.eq(DbDynamicImages::getDeleted,1);
            List<DbDynamicImages> dbDynamicImages = dbDynamicImagesMapper.selectList(wrapper);
            if (dbDynamicImages.size()>0){
                for (DbDynamicImages dbDynamicImage : dbDynamicImages) {
                    dbDynamicImage.setDeleted(0);
                    dbDynamicImagesMapper.updateById(dbDynamicImage);
                }
                return R.ok("删除动态对应图片成功");
            }
            log.info("动态没有对应图片");
//            if (dbDynamicImagesMapper.selectList(wrapper).size()>0) {
//                if(dbDynamicImagesMapper.delete(wrapper)>0){
//                    dbDynamicLogMapper.insert(new DbDynamicLog(dbDynamics.getUserId(),type,""+dbDynamics.getId(),ip,nickName+"删除了动态对应照片"));
//                    return R.ok("删除动态对应图片成功");
//                }else {
//                    return R.error("删除动态对应图片失败");
//                }
//            }
            return R.ok("删除动态成功");
        }else {
            return R.error("删除失败");
        }
    }

    @Override
    public R queryAllDynamicByType(Integer typeId) {
        LambdaQueryWrapper<DbDynamics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DbDynamics::getTypeId,typeId);
        wrapper.eq(DbDynamics::getProductTypeId,1);
        wrapper.eq(DbDynamics::getStatus,1);
        wrapper.eq(DbDynamics::getDeleted,1);
        List<DbDynamics> dbDynamics = dbDynamicsMapper.selectList(wrapper);
        if (dbDynamics.size()==0){
            return R.error("暂无该类型动态");
        }
        for (int i = 0; i < dbDynamics.size(); i++) {
            LambdaQueryWrapper<DbDynamicImages> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DbDynamicImages::getDynamicsId, dbDynamics.get(i).getId());
            wrapper1.eq(DbDynamicImages::getDeleted,1);
            List<DbDynamicImages> dbDynamicImages = dbDynamicImagesMapper.selectList(wrapper1);
            dbDynamics.get(i).setDbDynamicImages(dbDynamicImages);
            dbDynamicsMapper.updateById(dbDynamics.get(i));
        }
        return R.ok(dbDynamics);
    }

    @Override
    public R queryAllDynamicByUserId(int uid) {
        LambdaQueryWrapper<DbDynamics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DbDynamics::getUserId,uid);
        wrapper.eq(DbDynamics::getStatus,1);
        wrapper.eq(DbDynamics::getDeleted,1);
        List<DbDynamics> dbDynamics = dbDynamicsMapper.selectList(wrapper);
        if (dbDynamics.size()==0){
            return R.error("暂无该用户动态");
        }
//        List<DbDynamicImages> dbDynamicImages =null;
        for (int i = 0; i < dbDynamics.size(); i++) {
            LambdaQueryWrapper<DbDynamicImages> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DbDynamicImages::getDynamicsId, dbDynamics.get(i).getId());
            List<DbDynamicImages> dbDynamicImages = dbDynamicImagesMapper.selectList(wrapper1);
            dbDynamics.get(i).setDbDynamicImages(dbDynamicImages);
            dbDynamicsMapper.updateById(dbDynamics.get(i));
        }
//        Map<String, List<Object>> map = new HashMap<>();
//        map.put("dynamics", Collections.singletonList(dbDynamics));
//        map.put("images", Collections.singletonList(dbDynamicImages));
        return R.ok(dbDynamics);
    }

    @Override
    public R queryById(Integer id) {
        LambdaQueryWrapper<DbDynamics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DbDynamics::getId,id);
        wrapper.eq(DbDynamics::getStatus,1);
        wrapper.eq(DbDynamics::getDeleted,1);
        DbDynamics dbDynamics = dbDynamicsMapper.selectOne(wrapper);
        if (dbDynamics==null){
            return R.error("动态不存在");
        }
        LambdaQueryWrapper<DbDynamicImages> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DbDynamicImages::getDynamicsId,dbDynamics.getId());
        List<DbDynamicImages> dbDynamicImages = dbDynamicImagesMapper.selectList(wrapper1);
        dbDynamics.setDbDynamicImages(dbDynamicImages);
        dbDynamicsMapper.updateById(dbDynamics);
        return R.ok(dbDynamics);
    }

    @Override
    public R upload(MultipartFile file, Integer did,String ip) throws IOException{
        DbDynamics dbDynamics = dbDynamicsMapper.selectById(did);
        if (dbDynamics==null){
            return R.error("动态不存在");
        }
        DbProductType dbProductType = dbProductTypeMapper.selectById(dbDynamics.getTypeId());
        String type = dbProductType.getType();
        DbUser dbUser = dbUserMapper.selectById(dbDynamics.getUserId());
        String nickName = dbUser.getNickName();

        String imgName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
        String url = MyMinioUtil.upload(imgName, file.getBytes());
        if (url!=null){
            dbDynamics.setDisplayUrl(url);
            dbDynamicsMapper.updateById(dbDynamics);
//            logDao.insert(new LhUserLog(user.getId(),"用户上传头像",IP,"上传头像到资源服务器"));
            dbDynamicLogMapper.insert(new DbDynamicLog(dbDynamics.getUserId(),type,did+"",ip,nickName+"上传了封面图片"));
            return R.ok(url);
        }else {
            return R.error("sorry,网络异常,请稍后重试!");
        }
    }
}




